var express = require('express');
var router = express.Router();
var util = require("./util");
var Article = require("../models/article");

// 文章列表
router.get('/', function (req, res, next) {
    Article.find({}, function (err, data) {
        if (err) {
            res.render('page/bloglist', { title: 'CODE-SKY', articleList: [] });
        } else {
            data.forEach(item => {
                item.time = util.format(item.createTime, 'YYYY-MM-DD hh:mm:ss');
            })
            res.render('page/bloglist', { title: 'CODE-SKY', articleList: data });
        }
    });
});

// 文章列表(待删除按钮)
router.get('/list', function (req, res, next) {
    Article.find({}, function (err, data) {
        if (err) {
            res.render('list', { title: 'CODE-SKY', articleList: [] });
        } else {
            res.render('list', { title: 'CODE-SKY', articleList: data });
        }
    });
});

// 文章详情
router.get('/blog/:id', function (req, res, next) {
    const id = req.params.id;
    Article.find({_id: id}, function (err, data) {
        if (err) {
            res.render('page/blogdetail', { title: 'blog详情', blog: {} });
        } else {
            var blog = data[0] || {};
            blog.time = util.format(blog.createTime, 'YYYY-MM-DD hh:mm:ss');
            res.render('page/blogdetail', { title: 'blog详情', blog: blog });
        }
    });
});

router.post('/deleteblog', function (req, res, next) {
    var blogId = req.body.blogId;
    Article.findOneAndRemove({_id: blogId}, function (err, data) {
        if (err) {
            res.json({ code: 0, msg: "删除失败-" + err });
        } else {
            res.json({ code: 0, msg: "删除成功" + data });
        }
    })
})

module.exports = router;